package com.yuncheng.spcyApi.controller;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.schedule.ScheduleConstant;
import com.yuncheng.spcyApi.entity.SpcyScheduleMb;
import com.yuncheng.spcyApi.service.ISpcyScheduleMbService;
import com.yuncheng.spcyApi.utils.CronUtils;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Api(tags = "审评查验-定时任务模版接口")
@RestController
@RequestMapping("/api/spzx-spcy/scheduleMb")
public class ScheduleMbController {
    private static final Logger log = LoggerFactory.getLogger(ScheduleMbController.class);

    @Resource
    private ISpcyScheduleMbService spcyScheduleMbService;

    @Log(title = "查询定时任务模板")
    @ApiOperation(value = "查询定时任务模板")
    @GetMapping(value = "queryScheduleMbPage")
    public HttpResult<?> queryScheduleMbPage(SpcyScheduleMb scheduleMb,
                                             @RequestParam(name = "pageNo",defaultValue = "1")Integer pageNo,
                                             @RequestParam(name = "pageSize",defaultValue = "10")Integer pageSize){
        Page<SpcyScheduleMb> page = new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<SpcyScheduleMb> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(scheduleMb.getMbName()),SpcyScheduleMb::getMbName,scheduleMb.getMbName());
        queryWrapper.like(StringUtils.isNotBlank(scheduleMb.getMethodName()),SpcyScheduleMb::getMethodName,scheduleMb.getMethodName());
        queryWrapper.like(StringUtils.isNotBlank(scheduleMb.getBeanName()),SpcyScheduleMb::getBeanName,scheduleMb.getBeanName());

        if (scheduleMb.getJobStatus() != null){
            queryWrapper.eq(SpcyScheduleMb::getJobStatus,scheduleMb.getJobStatus());
        }

        queryWrapper.orderByDesc(SpcyScheduleMb::getCreateTime);
        IPage<SpcyScheduleMb> scheduleMbPage = spcyScheduleMbService.page(page, queryWrapper);
        return HttpResult.ok(scheduleMbPage);
    }

    /**
     * 添加定时任务
     *
     * @param sysJob
     * @return
     */
    @Log(title = "添加定时任务模板")
    @ApiOperation(value = "添加定时任务模板")
    @PostMapping("add")
    public HttpResult<?> add(@RequestBody SpcyScheduleMb sysJob) {
        if (StringUtils.isBlank(sysJob.getMbName())){
            return HttpResult.error("添加失败，模版名称不能为空");
        }
        if (StringUtils.isBlank(sysJob.getBeanName())){
            return HttpResult.error("添加失败，bean名称不能为空");
        }
        if (StringUtils.isBlank(sysJob.getMethodName())){
            return HttpResult.error("添加失败，方法名称不能为空");
        }
        // 判断是否存在该 bean对象
        if (!ScheduleConstant.getScheduleBeanList().contains(sysJob.getBeanName())){
            return HttpResult.error("系统中不存在，该bean对象【"+sysJob.getBeanName()+"】");
        }

        // 判断bean里面是否存在该方法
        boolean isExistMehtod = ScheduleConstant.getBeanInMethod(sysJob.getBeanName(), sysJob.getMethodName());
        if (!isExistMehtod){
            return HttpResult.error("【"+sysJob.getBeanName()+"】该bean对象中，不存在该方法【"+sysJob.getMethodName()+"】");
        }

        sysJob.setId(GetUuIdUtils.ReplaceUuId());
        if (sysJob.getMgdsfzzx() == null){
            sysJob.setMgdsfzzx(1);
        }

        // 计算cron表达式 0 0/30 * * * ?
        sysJob.setCronExpression(CronUtils.getCronWithStr(String.valueOf(sysJob.getMgdsfzzx())));

        if (sysJob == null){
            sysJob.setJobStatus(1);
        }

        boolean insert = spcyScheduleMbService.save(sysJob);
        if (!insert) {
            return HttpResult.error("添加失败，请刷新重试");
        }

        return HttpResult.ok("添加成功");
    }

    /**
     * 修改定时任务
     *
     * @param sysJob
     * @return
     */
    @Log(title = "修改定时任务模板")
    @ApiOperation(value = "修改定时任务模板")
    @PostMapping("update")
    public HttpResult<?> update(@RequestBody SpcyScheduleMb sysJob) {
        // 查询修改前任务
        if (StringUtils.isBlank(sysJob.getId())){
            return HttpResult.error("参数不能为空");
        }
        if (StringUtils.isBlank(sysJob.getMbName())){
            return HttpResult.error("添加失败，模版名称不能为空");
        }
        if (StringUtils.isBlank(sysJob.getBeanName())){
            return HttpResult.error("添加失败，bean名称不能为空");
        }
        if (StringUtils.isBlank(sysJob.getMethodName())){
            return HttpResult.error("添加失败，方法名称不能为空");
        }
        // 判断是否存在该 bean对象
        if (!ScheduleConstant.getScheduleBeanList().contains(sysJob.getBeanName())){
            return HttpResult.error("系统中不存在，该bean对象【"+sysJob.getBeanName()+"】");
        }

        // 判断bean里面是否存在该方法
        boolean isExistMehtod = ScheduleConstant.getBeanInMethod(sysJob.getBeanName(), sysJob.getMethodName());
        if (!isExistMehtod){
            return HttpResult.error("【"+sysJob.getBeanName()+"】该bean对象中，不存在该方法【"+sysJob.getMethodName()+"】");
        }

        SpcyScheduleMb mb = spcyScheduleMbService.getById(sysJob.getId());
        if (mb == null){
            return HttpResult.error("定时任务模版不存在，请刷新重试");
        }

        if (sysJob.getMgdsfzzx() == null){
            sysJob.setMgdsfzzx(1);
        }

        // 计算cron表达式 0 0/30 * * * ?
        sysJob.setCronExpression(CronUtils.getCronWithStr(String.valueOf(sysJob.getMgdsfzzx())));

        if (sysJob.getJobStatus() == null){
            sysJob.setJobStatus(1);
        }
        boolean update = spcyScheduleMbService.updateById(sysJob);
        if (!update) {
            return HttpResult.error("保存失败，请刷新重试");
        } else {

        }
        return HttpResult.ok("保存成功");
    }

    /**
     * 删除任务
     *
     * @param ids
     * @return
     */
    @Log(title = "删除定时任务模板")
    @ApiOperation(value = "删除定时任务模板")
    @ApiImplicitParam(name = "id",value = "id逗号分割")
    @DeleteMapping("delele")
    public HttpResult<?> del(@RequestParam("id") String ids) {
        // 先查询要删除的任务信息
        // 查询修改前任务
        if (StringUtils.isBlank(ids)){
            return HttpResult.error("参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        if (CollectionUtils.isNotEmpty(idsList)){
            for (String id:idsList){
                // 删除
                spcyScheduleMbService.removeById(id);
            }
        }

        return HttpResult.error("删除成功");
    }

    @Log(title = "通过id查询定时任务模板")
    @ApiOperation(value = "通过id查询定时任务模板")
    @GetMapping(value = "queryById")
    public HttpResult<?> queryById(String id){
        SpcyScheduleMb mb = spcyScheduleMbService.getById(id);
        return HttpResult.ok(mb);
    }
}
